package com.union.sqlitedemo.mySqlite;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import androidx.annotation.Nullable;

public class MySqilteHelpter extends SQLiteOpenHelper {

//    SQLiteOpenHelper
//     1.提供了oncreate onUpgrade 等回调函数
//     2.提供了操作数据库api

    public static final String DB_Name = "info.db";
    public static final int VERSION = 1;
    public static final String TABLE_NAME = "persion";


    public MySqilteHelpter(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
    }

    public MySqilteHelpter(@Nullable Context context) {
        super(context, DB_Name, null, VERSION);
    }

    /**
     * 数据库创建时候的回调
     *
     * @param sqLiteDatabase 创建的数据库对象
     */
    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        Log.d("Debug", "数据库创建成功");
        String sql = "create table persion(id Integer primary key,name vachar(100))";
        sqLiteDatabase.execSQL(sql);
        onUpgrade(sqLiteDatabase, 1, VERSION);
    }

    /**
     * 数据库更新
     *
     * @param sqLiteDatabase
     * @param i
     * @param i1
     */
    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
        // 卸载app进来之后   直接走oncreate方法  不走onUpgrade方法    但是app里面用到了下面更新的东西  怎么处理
//         第一种处理方式    在oncreate方法中手动的调用 onUpgrade方法
        Log.d("Debug", "数据库更新操作老版本号为" + i + "新版本号为" + i1);
        if (i < 2) {
            String sql = "create table book(id Integer primary key,name vachar(100))";
            sqLiteDatabase.execSQL(sql);
        }
        if (i < 3) {
            String sql = "alter table Book add column category_id Integer default 0";
            sqLiteDatabase.execSQL(sql);
        }
//        if (i<4){
//            String delete = "alter table Book drop  column category_id";
//            sqLiteDatabase.execSQL(delete);
//        }
    }

    /**
     * 打开数据库的回调
     *
     * @param db
     */
    @Override
    public void onOpen(SQLiteDatabase db) {
        super.onOpen(db);
        Log.d("Debug", "打开数据库操作");

    }
}
